package org.example.lease.service.dutyhandler.loginduty.impl;

import org.example.common.exception.LeaseException;
import org.example.lease.model.entities.SystemUser;
import org.example.lease.model.result.ResultCodeEnum;
import org.example.lease.service.SystemUserService;
import org.example.lease.service.dutyhandler.loginduty.AbstractLoginHandler;
import org.example.lease.vo.login.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用户名验证处理器
 */
@Component
public class UsernameValidateHandler extends AbstractLoginHandler {
    private final SystemUserService systemUserService;

    @Autowired
    public UsernameValidateHandler(SystemUserService systemUserService) {
        this.systemUserService = systemUserService;
    }

    @Override
    protected String doHandle(LoginVo loginVo) {
        String usernameFromVo = loginVo.getUsername();
        SystemUser systemUser = systemUserService.selectSystemUserByUserName(usernameFromVo);
        if (systemUser == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        if (!systemUser.getUsername().equals(usernameFromVo)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        // 将用户信息存储到LoginVo中，供后续处理器使用
        loginVo.setSystemUser(systemUser);
        return null;
    }
}